from datetime import datetime
from app import db
from sqlalchemy import Index

class UserAttribute(db.Model):
    """用户属性模型（可选自定义属性）"""
    __tablename__ = 'user_attributes'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    key = db.Column(db.String(50), nullable=False, comment='属性键名')
    value = db.Column(db.String(255), comment='属性值')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    user = db.relationship('User', backref='attributes')
    
    # 复合唯一索引（一个用户的一个属性键只能有一个值）
    __table_args__ = (
        Index('idx_user_key', 'user_id', 'key', unique=True),
    )
    
    def __repr__(self):
        return f'<UserAttribute user_id={self.user_id}, key={self.key}, value={self.value}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'key': self.key,
            'value': self.value,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
    
    @classmethod
    def get_user_attributes(cls, user_id):
        """获取用户的所有属性"""
        attributes = cls.query.filter_by(user_id=user_id).all()
        return {attr.key: attr.value for attr in attributes}
    
    @classmethod
    def set_user_attribute(cls, user_id, key, value):
        """设置或更新用户属性"""
        # 查找现有属性
        existing = cls.query.filter_by(user_id=user_id, key=key).first()
        
        if existing:
            # 更新现有属性
            if value is None:
                # 如果值为None，删除该属性
                db.session.delete(existing)
                return None
            else:
                existing.value = value
                existing.updated_at = datetime.now()
                return existing
        else:
            # 创建新属性
            if value is not None:
                new_attr = cls(
                    user_id=user_id,
                    key=key,
                    value=value
                )
                db.session.add(new_attr)
                return new_attr
        return None
    
    @classmethod
    def batch_set_attributes(cls, user_id, attributes_dict):
        """批量设置用户属性"""
        results = []
        for key, value in attributes_dict.items():
            result = cls.set_user_attribute(user_id, key, value)
            if result:
                results.append(result)
        return results
    
    @classmethod
    def replace_user_attributes(cls, user_id, attributes_dict):
        """完全替换用户属性（删除所有现有属性，然后创建新属性）"""
        # 1. 删除用户的所有现有属性
        cls.query.filter_by(user_id=user_id).delete()
        
        # 2. 创建新属性
        results = []
        for key, value in attributes_dict.items():
            if value is not None:  # 只创建非空值的属性
                new_attr = cls(
                    user_id=user_id,
                    key=key,
                    value=value
                )
                db.session.add(new_attr)
                results.append(new_attr)
        
        return results
    
    @classmethod
    def delete_user_attribute(cls, user_id, key):
        """删除用户属性"""
        attribute = cls.query.filter_by(user_id=user_id, key=key).first()
        if attribute:
            db.session.delete(attribute)
            return True
        return False 